package middleware

import (
	"net/http"
	"strings"
	"time"

	"github.com/golang-jwt/jwt/v4"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
)

type JwtMiddleware struct {
	AccessSecret string
}

func NewJwtMiddleware(secret string) *JwtMiddleware {
	return &JwtMiddleware{AccessSecret: secret}
}

func (m *JwtMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {

		if strings.HasPrefix(r.URL.Path, "/api/v1/login") {
			next(w, r)
			return
		}

		tokenString := r.Header.Get("Authorization")
		if tokenString == "" {
			httpx.Error(w, http.ErrNoCookie)
			return
		}

		token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
			if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
				return nil, jwt.ErrSignatureInvalid
			}
			return []byte(m.AccessSecret), nil
		})
		if err != nil || !token.Valid {
			logx.Error("JWT 验证失败: ", err)
			httpx.Error(w, http.ErrNoCookie)
			return
		}

		claims, ok := token.Claims.(jwt.MapClaims)
		if !ok || !token.Valid {
			httpx.Error(w, http.ErrNoCookie)
			return
		}

		// 可以在这里检查 token 的其他信息，比如过期时间
		if exp, ok := claims["exp"].(float64); ok && int64(exp) < time.Now().Unix() {
			httpx.Error(w, http.ErrNoCookie)
			return
		}

		// JWT 验证成功，继续处理下一个请求
		next(w, r)
	}
}
